package com.lyc.wx.controller;

import com.lyc.bean.Message;
import com.lyc.bean.User;
import com.lyc.mvc.ResponseBody;
import com.lyc.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class UserController {

    private static final String SQL_COURIER = "SELECT USERPHONE phone FROM COURIER";

    @ResponseBody("/wx/loginSms.do")
    public String sendSms(HttpServletRequest request, HttpServletResponse response){
        String userPhone = request.getParameter("userPhone");
        String code = RandomUtil.getCode() + "";
        //String code = "123456";
        boolean flag = SMSUtil.loginSMS(userPhone, code);
        //boolean flag = true;
        Message msg = new Message();
        if (flag){
            // 短信发送成功
            msg.setStatus(0);
            msg.setResult("验证码已发送，请查收");
        }else {
            // 短信发送失败
            msg.setStatus(-1);
            msg.setResult("验证码发送失败！请检查手机号或稍后再试");
        }
        UserUtil.setLoginSms(request.getSession(), userPhone, code);
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        String userPhone = request.getParameter("userPhone");
        String userCode = request.getParameter("code");
        String sysCode = UserUtil.getLoginSms(request.getSession(), userPhone);
        Message msg = new Message();
        if (sysCode == null){
            // 这个手机号未获取短信
            msg.setStatus(-1);
            msg.setResult("手机号码未获取短信");
        }else if (sysCode.equals(userCode)){
            // 这里手机号码和短信一致，登录成功
            User user = new User();
            ArrayList<String> data = new ArrayList<>();
            // 1.获取数据库的连接
            Connection conn = DruidUtil.getConnection();
            PreparedStatement state = null;
            ResultSet result = null;
            // 2.预编译SQL语句
            try {
                state = conn.prepareStatement(SQL_COURIER);
                // 3.填充参数（可选）
                // 4.执行SQL语句
                result = state.executeQuery();
                // 5.获取执行的结果
                while (result.next()){
                    data.add(result.getString("phone"));
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                // 6.资源的释放
                DruidUtil.close(conn, state, result);
            }
            // 将sql语句获取到的phone值拼接成一个字符串
            StringBuffer sb = new StringBuffer();
            for(String item : data){
                sb.append(item);
            }
            int i = sb.indexOf(userPhone);// 用indexOf字符串中是否有前端传递过来的userPhone
            if (i > 0){
                // 快递员
                msg.setStatus(1);
                user.setUser(false);
            }else {
                // 用户
                msg.setStatus(0);
                user.setUser(true);
            }
            user.setUserPhone(userPhone);
            UserUtil.setWxUser(request.getSession(), user);
        }else {
            // 这里是验证码不一致，登录失败
            msg.setStatus(-2);
            msg.setResult("验证码不一致，请检查");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/userInfo.do")
    public String userInfo(HttpServletRequest request, HttpServletResponse response){
        User user = UserUtil.getWxUser(request.getSession());
        boolean isUser = user.isUser();
        Message msg = new Message();
        if (isUser){
            msg.setStatus(0);
        }else {
            msg.setStatus(1);
        }
        msg.setResult(user.getUserPhone());
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/loginOut.do")
    public String loginOut(HttpServletRequest request, HttpServletResponse response){
        // 1.销毁session
        request.getSession().invalidate();
        // 2.给客户端回复消息
        Message msg = new Message(0);
        return JSONUtil.toJSON(msg);
    }
}
